<?php

namespace App\Http\Controllers\Admin\Play;

use App\Models\PlayType;
use App\Org\Developer\Helper;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class TypeController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('admin.play.type.index');
    }

    /**
     * 异步获取列表数据
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
     */
    public function lists(Request $request)
    {
        if ($request->ajax()) {
            $offset = intval($request->get('start'));

            $paginate = PlayType::select(['id', 'title', 'type', 'created_at', 'updated_at'])->orderBy('id', 'asc')
                ->paginate(self::PAGE_SIZE, ['*'], 'page', intval($offset / self::PAGE_SIZE) + 1);

            $data = [];
            foreach ($paginate as $item) {

                $data[] = [
                    $item->id,
                    $item->title,
                    PlayType::getTypeName($item->type),
                    $item->created_at->toDateTimeString(),
                    $item->updated_at->toDateTimeString(),
                    '<a href="' . url('admin/playType/' . $item->id.'/edit') . '" type="button" class="btn btn-primary btn-xs"><i class="fa fa-edit"></i> 编辑</a> <a type="button" class="btn btn-danger btn-xs btn-remove" data-id="'. $item->id .'"><i class="fa fa-remove"></i> 删除</a>',
                ];
            }

            $records = [
                'data' => $data,
                'draw' => intval($request->get('draw')),
                'recordsTotal' => $paginate->total(),
                'recordsFiltered' => $paginate->total(),
            ];

            return response()->json($records);
        } else {
            return redirect()->guest('admin/login');
        }
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('admin.play.type.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        // 验证
        $this->validate($request, [
            'title' => 'required|unique:play_types|min:2',
        ], [
            'required' => ':attribute 必须.',
            'unique' => ':attribute 已存在.',
            'min' => ':attribute 不能少于 2 位.',
        ]);

        try {
            $createModel = PlayType::create(['title' => $request->input('title'), 'type' => mt_rand(0, 3)]);
            if (isset($createModel) && $createModel->id) {
                return redirect('admin/playType');
            }
            return back()->with('status', '类型添加失败.');
        } catch (\Exception $e) {
            return back()->with('status', '类型添加失败.'. $e->getMessage());
        }
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        // 检查 id 是否合法
        if (Helper::idInvalid($id)) {
            return back()->with('status', '类型 id 不合法.');
        }
        try {
            $updateModel = PlayType::select(['id', 'title'])->find($id);
            if (!(isset($updateModel) && $updateModel->title)) {
                return redirect('admin/playType')->with('status', '要修改的类型不存在.');
            }
            return view('admin.play.type.update')->with(['model' => $updateModel]);
        } catch (\Exception $e) {
            return back()->with('status', '类型修改失败.'. $e->getMessage());
        }
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        // 检查 id 是否合法
        if (Helper::idInvalid($id)) {
            return back()->with('status', '类型 id 不合法.');
        }

        try {
            // 检查该类型是否存在
            $updateModel = PlayType::select(['id', 'title'])->find($id);
            if (!(isset($updateModel) && $updateModel->title)) {
                return redirect('admin/playType')->with('status', '要修改的类型不存在.');
            }

            // 如果 id 和 title 都一样，表示不修改
            if ($updateModel->title == $request->input('title')) {
                return back()->with('status', '没有任何修改.');
            }

            // 验证
            $this->validate($request, [
                'title' => 'required|unique:play_types|min:2',
            ], [
                'required' => ':attribute 必须.',
                'unique' => ':attribute 已存在.',
                'min' => ':attribute 不能少于 2 位.',
            ]);

            $updateModel->title = $request->title;
            $result = $updateModel->save();
            if ($result) {
                return redirect('admin/playType');
            }
            return back()->with('status', '类型修改失败.');
        } catch (\Exception $e) {
            return back()->with('status', '类型修改失败.'. $e->getMessage());
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        // return response()->json(['code' => 200, 'id' => $id]);
        
        // 检查 id 是否合法
        if (Helper::idInvalid($id)) {
            return response()->json(['code' => 4000]);
            // return back()->with('status', '类型 id 不合法.');
        }

        try {
            // 检查该类型是否存在
            $updateModel = PlayType::select(['id', 'title'])->find($id);
            if (!(isset($updateModel) && $updateModel->title)) {
                return response()->json(['code' => 4001]);
                // return redirect('admin/playType')->with('status', '要删除的类型不存在.');
            }

            $result = $updateModel->delete();
            if ($result) {
                return response()->json(['code' => 200]);
                // return redirect('admin/playType');
            }
            return response()->json(['code' => 4002]);
            // return back()->with('status', '类型删除失败.');
        } catch (\Exception $e) {
            return response()->json(['code' => 5555]);
            // return back()->with('status', '类型删除失败.'. $e->getMessage());
        }
    }
}
